import { createBrowserRouter } from 'react-router'
import Home from '../pages/Home'
import About from '../pages/About'
import Layout from '../layout'
import NotFound from '../layout/404'
// import { useRouteError } from 'react-router'

const data = [
  {name: '张三', age: 18},
  {name: '李四', age: 20},
  {name: '王五', age: 22},
]

const sleep = (ms: number) => {
  return new Promise((resolve) => {
    setTimeout(resolve, ms)
  })
}

const router = createBrowserRouter([
  {
    path: '/',
    Component: Layout,
    children: [
      {
        path: 'home/:id',
        // index: true,  // 默认子路由
        Component: Home,
        loader: async ({params}) => {
          console.log('loader params',params);
          
          await sleep(2000)

          return {
            data,
            success: true
          }
        },
        action: async ({request}) => {
          const formData = await request.formData()
          const json = Object.fromEntries(formData)
          console.log('action json',json);
          console.log('action formData',formData);
          await sleep(2000)
          return {
            success: true,
            message: '提交成功'
          }
        }
      },
      {
        path: 'about',
        // Component: About,
        lazy: async () => {
          await sleep(2000)
          const about = await import('../pages/About')  // 打包后会单独分包
          return {
            Component: about.default
          }
        }
      },
    ]
  },
  {
    path: '*',
    Component: NotFound,
  }
])

export default router
